#include <iostream>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>


int main() {
    std::cout << "hello ChatCinema" << std::endl;
    // 创建套接字
    int sock_fd = socket(AF_INET,SOCK_STREAM, 0);

    if (sock_fd == -1) {
        perror("socket error");
        return -1;
    }

    struct sockaddr_in saddr;
    
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = INADDR_ANY;
    saddr.sin_port = htons(9999);
    // sock_fd是用于连接的fd，把ip和端口bind上去
    int ret = bind(sock_fd, (struct sockaddr *)& saddr, sizeof(saddr));

    if (ret == -1) {
        perror("bind error");
        return -1;
    }

    // 开始监听是否有客户端连接
    ret = listen(sock_fd, 128);
    if (ret == -1) {
        perror("listen error");
        return -1;
    } 

    sockaddr_in caddr;
    unsigned int caddr_len = sizeof(caddr);
    // accept阻塞，当有客户端连接的时候返回con_fd，该fd用于通信。这里才真正开始监听。
    int con_fd = accept(sock_fd, (sockaddr*) &caddr, &caddr_len);
    if (con_fd == -1) {
        perror("accept error");
        return -1;
    }

    char ip[32];
    inet_ntop(AF_INET, &caddr.sin_addr.s_addr, ip, sizeof(ip));
    std::cout << "[connection] ip: " << ip << ", port: " << caddr.sin_port << std::endl;
    
    while (true) {
        char buff[1024];
        int len = recv(con_fd, buff, sizeof(buff), 0);
        if (len > 0) {
            std::cout << "[message] " << buff << std::endl;
            send(con_fd, buff, len, 0);
        }
        else if (len == 0) {
            std::cout << "[connection lost]" << std::endl;
            break;
        }
        else {
            perror("recv error");
            break;
        }
    }

    close(sock_fd);
    close(con_fd);

    return 0;
}